package demo3;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    // 定义一个阻塞队列来组织任务
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    public MyThreadPool (int threadNum) {
        if (threadNum == 0) {
            throw new IllegalArgumentException("线程数量必须大于零...");
        }
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(() -> {
                // 不停的去扫描队列
                while (true) {
                    // 从队列中提取出任务
                    try {
                        Runnable runnable = queue.take();
                        // 执行任务
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            // 启动线程
            thread.start();
        }
    }
    /**
     * 提交任务到线程池
     * @param runnable 具体的任务
     * @throws InterruptedException
     */
    public void submit (Runnable runnable) throws InterruptedException {
        if (runnable == null) {
            throw new IllegalArgumentException("任务不能为空...");
        }
        // 把任务加入到队列
        queue.put(runnable);
    }

}
